
#include "../libpatches.h"
#include "randlin.h"
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <math.h>

static void module_randlin_processor(module m);
void module_randlin_customizer(module m, char * name, char * value);

void module_randlin_initializer(module m) {
	m->customizer = module_randlin_customizer;
}

void module_randlin_customizer(module m, char * name, char * value) {

	int i;
	//output * o;

	customizer_count_inputs_only(m, name, value);
	if (m->input_count && ! m->inputs) {
		make_outputs(m, m->input_count * 2);
		make_inputs(m, 2);
		make_buffer(m, m->output_count/2 + 1);
		m->input_names[0] = "in";
		m->input_names[1] = "amount";
		patch_one(m->inputs + 1);

		m->buffer[0] = DBL_MAX;

		for (i = 0; i < m->output_count; i += 2)
			*m->outputs[i] = rand() / (double) RAND_MAX;

		m->processor = module_randlin_processor;
	} 
}

static void module_randlin_processor(module m) {
	input p = m->named_inputs[0];
	input amount = m->named_inputs[1];
	sample * last = m->buffer;
	sample * s;
	output * o;
	int c;

	if (**p < *last)
		for (
			o = m->outputs, 
			c = m->buffer_size - 1,
			s = m->buffer + 1;
			c;
			--c, ++s, o += 2
		) {
			*s = **o;
			**o = rand() / (double) RAND_MAX;
		}

	int q = **p < **amount;
	double y = **p / **amount;
	for (
		o = m->outputs, 
		c = m->buffer_size - 1,
		s = m->buffer + 1;
		c;
		--c, ++s, o += 2
	) **(o + 1) = (q ? *s + (**o - *s) * y : **o);

	*last = **p;
}
